<!--  -->
<template>
  <div class="box">
    <div class="left">
      <el-input
        v-model="filterText"
        class="left_input"
        placeholder="输入关键字进行过滤"
      />

      <el-tree
        ref="tree"
        class="filter-tree"
        :data="data"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      />
    </div>
    <div class="right">
      <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab">
        <el-tab-pane
          v-for="(item) in editableTabs"
          :key="item.name"
          :label="item.title"
          :name="item.name"
        >
          <div class="top">
            <div class="editor-container">
              <json-editor ref="jsonEditor" v-model="item.code" language="sql" :ifshow="false" />
            </div>
            <el-button style="margin:5px;" @click="select">查询</el-button>
          </div>
          <div class="bottom">
            <el-table
              :data="editableTabs[selectIndex].talbe"
              style="width: 100%"
            >
              <el-table-column
                v-for="(item2) in editableTabs[selectIndex].talbeField"
                :key="item2"
                :prop="item2"
                :label="item2"
              />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { apiGetList, apiGetBase, apiGetTbale, apiExecute } from '@/api/dataAnalysis/index'
import JsonEditor from '@/components/JsonEditor'

export default {
  name: 'Index',
  // import引入的组件需要注入到对象中才能使用
  components: { JsonEditor },
  data() {
    // 这里存放数据
    return {
      // 筛选
      filterText: '',
      // 树状结构
      data: [],
      // 树状结构
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 选中tab
      editableTabsValue: '0',
      // tal
      editableTabs: [],
      // 查询字段
      sql: '',
      selectIndex: 0
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    apiGetList().then((response) => {
      console.log(response.data)
      response.data.forEach(item => {
        item.label = item.name
      })
      this.data = response.data
    })
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  // 方法集合
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 新增tab
    addTab(data) {
      console.log(this.editableTabs)
      let ifGo = false
      // tab存在
      this.editableTabs.forEach(item => {
        if (item.title === data.label) {
          this.editableTabsValue = item.name
          ifGo = true
        }
      })
      if (ifGo) {
        return false
      }
      const date = Date.parse(new Date()) / 1000
      this.editableTabs.push({
        code: '',
        talbe: [],
        talbeField: [],
        title: data.label,
        name: date + '',
        content: 'New Tab content',
        data
      })
      console.log(this.editableTabs)
      this.editableTabsValue = date + ''
    },
    // 删除tab
    removeTab(targetName) {
      const tabs = this.editableTabs
      let activeName = this.editableTabsValue
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              activeName = nextTab.name
            }
          }
        })
      }

      this.editableTabsValue = activeName
      this.editableTabs = tabs.filter(tab => tab.name !== targetName)
    },
    // tree点击
    nodeClick(e) {
      // console.log(e)
      // 点击表结束,新增tab
      if (e.end) {
        this.addTab(e)
        return false
      }
      // 点击库,查表
      if (e.table) {
        const param = {
          id: e.baseId,
          databaseName: e.label
        }
        apiGetTbale(param).then(response => {
          const data = []
          console.log(response.data)
          response.data.forEach(item => {
            data.push({
              label: item,
              id: (new Date()).valueOf(),
              end: true,
              baseId: e.baseId,
              kuName: e.label
            })
          })
          e.children = data
        })
      } else {
        // 点击链接,查库
        apiGetBase(e.id).then(response => {
          const data = []
          console.log(response.data)
          response.data.forEach(item => {
            data.push({
              children: [],
              baseId: e.id,
              label: item.databaseName,
              id: (new Date()).valueOf(),
              table: true
            })
          })
          e.children = data
        })
      }
    },
    // 执行查询
    select() {
      this.editableTabs.forEach((item, index) => {
        if (item.name === this.editableTabsValue) {
          const data = {
            sql: item.code,
            id: item.data.baseId,
            databaseName: item.data.kuName
          }
          apiExecute(data).then(response => {
            item.talbe = response.data
            if (response.data.length > 0) {
              item.talbeField = Object.keys(response.data[0])
            }
            this.selectIndex = index
            console.log(item.talbeField, 'aa')
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.box{
  margin: 10px;
  display: flex;
  min-height: calc(100vh - 124px);
}
.left{
  width: 180px;
  border: 1px solid #ccc;
  .left_input{
    width: 80%;
    margin: 15px;
  }
}
.right{
  margin-left: 20px;
  flex: 1;
  border: 1px solid #ccc;
  .el-tab-pane{
    height: 100%;
    padding: 15px;
    display: flex;
    flex-direction: column;
  }
  .top{
    width: 100%;
    height: 400px;
    border: 1px solid #ccc;
    margin-bottom: 15px;
  }
  .bottom{
    width: 100%;
    border: 1px solid #ccc;
    overflow-x: scroll;
  }
}
</style>
